package com.hmall.consumer.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmall.client.ItemClient;
import com.hmall.client.OrderClient;
import com.hmall.client.SearchClient;
import com.hmall.client.UserClient;
import com.hmall.pojo.Item;
import com.hmall.pojo.ItemDoc;
import com.hmall.pojo.Order;
import com.hmall.pojo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
@Slf4j
public class SpringRabbitListener {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderClient orderClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private SearchClient searchClient;


    /**
     * 消息处理机制 -- RepublishMessageRecoverer
     * @param msg
     */
    /*@RabbitListener(bindings = @QueueBinding(
            value = @Queue("error.queue"),
            exchange = @Exchange("error.direct"),
            key = "error"
    ))
    public void listenErrorQueue(String msg){
        log.debug("消费者接收到error.queue的消息：【" + msg + "】");
    }*/

    /**
     * 延迟交换机处理超时订单
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("delay.queue"),
            exchange = @Exchange(value = "delay.direct",delayed = "true"),
            key = "delay"
    ))
    public void listenDelayQueue(String id){
        log.info("延迟队列监听到数据。。。超时订单id：{}",id);
        //根据id查找订单数据
        Order order = orderClient.queryOrderById(Long.parseLong(id));

        //处理幂等问题
        if (5 == order.getStatus()) {
            log.info("处理幂等问题。。。");
            return;
        }

        //判断order状态
        if (1 == order.getStatus()) {
            OrderDetail orderDetail = orderClient.queryOrderDetail(Long.parseLong(id));

            order.setStatus(5);
            order.setCloseTime(new Date());
            order.setUpdateTime(new Date());

            //更新order表，返回item表库存、user表金额
            orderClient.updateOrder(order);
            itemClient.refund(orderDetail.getItemId().toString(),orderDetail.getNum().toString());
            userClient.refund(order.getUserId().toString(),order.getTotalFee().toString());
            log.info("处理超时订单成功！！！id：{}",id);
        }
    }

    /**
     * 商品修改es实时更新
     * @param item
     * @throws IOException
     */
    @RabbitListener(queuesToDeclare = @Queue("item.queue"))
    public void listenItem(Item item) throws IOException {
        log.info("商品修改es实时更新：{}",item);
        searchClient.updateES(item);
    }
}
